﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.entity.Device;
using tcm.Filters;
using tcm.request.Device;
using tcm.response;
using tcm.utils;

namespace tcm.Controller.DeviceManage
{
    [ApiController]
    [Route("tcm/phmlog")]
    public class PhmLogController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public PhmLogController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        #region 管理进出口记录
        /// <summary> 
        /// 查询进出口记录列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "equipment:phmlog:list")]
        public DataResponse<List<PhmLogSelect>> GetList([FromQuery] PhmLogRequest request)
        {
            var sql = new StringBuilder();

            _=sql.Append("select t.*, s.site_name,s.id as site_id,d.device_name,c.cabinet_no,pl.list_name as phm_list_name " +
                        "from tcm_phm_log t " +
                        "left join tcm_cabinet c on c.id=t.cabinet_id " +
                        "left join tcm_device d on d.id=c.device_id " +
                        "left join tcm_site s on s.id=d.site_id " +
                        "left join tcm_phm_list pl on pl.id=t.phm_list_id " +
                        "where 1=1 ");

            if (request.cabinet_id>=0)
                _=sql.Append(string.Format(" and t.cabinet_id={0}", request.cabinet_id));

            _=sql.Append(" order by t.create_date desc ");
            var dbres = GCCEntrance.DBManager.GlobalDB.Select<PhmLogSelect>()
                .WithSql(sql.ToString())
                .Count(out var count)
                .Page(request.PageIndex ?? 1, request.PageSize!=0 ? request.PageSize : int.MaxValue)
                .ToList();

            foreach (var item in dbres)
            {
                var sqlstr = new StringBuilder();
                _=sqlstr.Append(string.Format("select pl.phm_list_id,pl.phm_num,p.*,pl.phm_num*{0} as phm_total from  tcm_phm_list_relation pl join tcm_pharmaceutical p on  pl.phm_id= p.id", item.num));
                _=sqlstr.Append(string.Format(" where pl.phm_list_id = '{0}' ", item.phm_list_id));
                var pharmaceuticalInfos = GCCEntrance.DBManager!.LocalDB!.Select<PharmaceuticalInfo>()
                    .WithSql(sqlstr.ToString())
                   .ToList();         

                item.pharmaceuticals.AddRange(pharmaceuticalInfos);
            }
              
            return HandleData(dbres, count);
        }

        /// <summary>
        /// 添加出入库记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "equipment:phmlog:add")]
        public DataResponse<bool> AddDevice([FromBody] PhmLogDto request)
        {
            var saveRes = false;
            try
            {
                if (request.cabinet_id<=0)
                    throw new Exception("药柜id不能为空");
                if (request.phm_list_id<=0)
                    throw new Exception("处方单id不能为空");

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {

                    var cabinet=GCCEntrance.DBManager!.LocalDB!.Select<Cabinet>(request.cabinet_id)
                    .First();
                    if (cabinet!=null)
                    {
                        var isHave = cabinet.is_have;   
                        int num = request.num;
                        //入库
                        if (request.phm_use==1)
                        {
                            isHave=1;
                        }
                        //出库或销毁
                        if (request.phm_use==2||request.phm_use==3)
                        {
                            if (cabinet.num<num)
                                throw new Exception("库存不足");

                            if (cabinet.num==num)

                                isHave=0;
                            else if (cabinet.num>num)
                                isHave=1;

                            num = -num;
                        }
                           
                        if (GCCEntrance.DBManager!.LocalDB!.Update<Cabinet>(request.cabinet_id)
                            .Set(c => c.num == (c.num+num))
                            .Set(c => c.is_have, isHave)
                            .Set(c => c.phm_list_id==request.phm_list_id)
                            .ExecuteAffrows() != 1)
                        {
                            throw new Exception("更新库存失败");
                        }

                        request.Create(_context, HttpContext.GetToken()).Wait();
                        PhmLog phmLog = BeanUtils.copy<PhmLog, PhmLogDto>(request);
                        phmLog.phm_list_id = request.phm_list_id;
                        if (GCCEntrance.DBManager!.LocalDB!.Insert(phmLog).ExecuteAffrows() != 1)
                        {
                            throw new Exception("新增记录失败");
                        }
                    }
                    else
                    {
                        throw new Exception("药柜不存在");
                    }

                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>("新增失败:"+exe.Message);
            }

            return HandleData(saveRes);
        }


        ///// <summary>
        ///// 查询设备表详情
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet("get/{id}")]
        //public DataResponse<Device> GetDevice([FromRoute] long id)
        //{
        //    var res = GCCEntrance.DBManager!.LocalDB!.Queryable<Device>().Where(x => x.id==id).First();

        //    return HandleData(res);
        //}



        ///// <summary>
        ///// 更新设备
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("update")]
        //[TCMAuth(permission: "equipment:device:update")]
        //public DataResponse<bool> UpdateDevice([FromBody] DeviceDto request)
        //{
        //    var saveRes = false;
        //    if (request.id<=0)
        //        return HandleData(saveRes, "id为空");
        //    try
        //    {
        //        GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
        //        {
        //            var device = GCCEntrance.DBManager.LocalDB.Select<Device>().Where(a => a.id == request.id).First();
        //            if (device==null)
        //                throw new Exception("设备不存在");
        //            request.create_by = device.create_by;
        //            request.create_date = device.create_date;
        //            request.Modify(_context, HttpContext.GetToken()).Wait();

        //            BeanUtils.copy<Device, DeviceDto>(request, ref device);

        //            if (GCCEntrance.DBManager.LocalDB.Update<Device>(request.id).SetSource(device).ExecuteAffrows()<=0)
        //            {
        //                throw new Exception();
        //            }      
        //            saveRes=true;
        //        });
        //    }
        //    catch (Exception exe)
        //    {
        //        return SystemError<bool>("新增异常，请重试。"+exe.Message);
        //    }
        //    return HandleData(saveRes);
        //}

        #endregion
    }
}
